# Created by yang
import datetime
import importlib
import os
import sys
import pickle
import time
import json
import requests

from autotest import VAR, BASE_DIR
from ..utils import time_util

sql = VAR.sql
logger = VAR.logger

DOMAIN = "https://lcts{}.ssjlicai.com".format(VAR.env[-1:])
LOGIN_URL = '/userws/ws/login/v1/loginByPwd'

from .Asset import *


def isZc(pno):
    if pno.startswith("ZC"):
        return True
    else:
        return False


def selectTemplate():
    """打印模板"""
    sql.exec(
        "SELECT id,tmp_name,time_unit_code FROM `finance_fixin_product`.`t_fixin_zc_product_tmp` ORDER BY id DESC LIMIT 50")
    sql.exec(
        "SELECT id,tmp_name,product_term FROM `finance_fixin_product`.`t_fixin_periodic_product_tmp` ORDER BY id DESC LIMIT 50")


def selectProduct(pno):
    """获取产品信息"""
    pno = handlePno(pno)
    if isZc(pno):
        res = sql.exec('SELECT * FROM `finance_fixin_product`.`t_fixin_zc_product` WHERE pno  = "{}";'.format(pno))
    else:
        res = sql.exec(
            'SELECT * FROM `finance_fixin_product`.`t_fixin_periodic_product` WHERE pno  = "{}";'.format(pno))

    logger.info("获取到的标的信息：{}".format(res))
    return res


def handlePno(pno):
    if "-" not in pno:
        return pno
    else:
        return pno[:pno.index("-")]


def updateProduct(pno, change=True, **kwargs):
    """
    更新产品信息
    :param pno: 
    :param change: 是否更改，有些比如是时间字符串，需要转化成时间对象在update到数据库
    :param kwargs: 
    :return: 
    """
    pno = handlePno(pno)

    if change:
        for key in kwargs:
            if "time" in key:
                logger.info("将key：{}时间字符串：{}改为datetime对象".format(key, kwargs[key]))
                kwargs[key] = datetime.datetime.strptime(kwargs[key], "%Y-%m-%d %H:%M:%S")

    if isZc(pno):
        table_name = ' `finance_fixin_product`.`t_fixin_zc_product` '
    else:
        table_name = ' `finance_fixin_product`.`t_fixin_periodic_product` '

    sql.update(table_name=table_name, where={"pno": pno}, **kwargs)

    selectProduct(pno)

    cleanCache(pno)


def dumpProduct(pno):
    """将产品的信息保存成文件"""
    pno = handlePno(pno)

    product_info = selectProduct(pno)[0]

    path = os.path.join(BASE_DIR, VAR.data, pno)
    with open(path, 'wb') as f:  # pickle只能以二进制格式存储数据到文件
        f.write(pickle.dumps(product_info))  # dumps序列化源数据后写入文件


def loadProduct(pno):
    """获取产品信息"""
    pno = handlePno(pno)
    path = os.path.join(BASE_DIR, VAR.data, pno)

    if not os.path.exists(path):
        raise Exception("在路径{}未找到源数据，请检查pno：{}是否传递正确".format(path, pno))

    with open(path, 'rb') as f:  # pickle只能以二进制格式存储数据到文件
        data = pickle.loads(f.read())  # 使用loads反序列化

    logger.info("反序列化出来的数据:{}".format(data))

    # 将信息写入数据库
    data.pop("id")
    data.pop("pno")

    updateProduct(pno, change=False, **data)


def post(url, json_dict=None, data=None):
    """
    发送post请求
    :param url: 
    :param data: 
    :param json_dict: 一个dict
    :return: 
    """
    logger.info("请求url：{},data:{},json:{}".format(url, data, json_dict))
    response = requests.post(url, data=None, json=json_dict)
    logger.info(json.dumps(response.json(), indent=4, ensure_ascii=False))
    return response.json()


def cleanCache(*args, cleanAll=False):
    """
    清除缓存
    :param args: 模糊清除，可以传多个参数，如一次清除多个标的的缓存
    :param cleanAll: 是否全部清除
    :return: 
    """
    logger.info("清除缓存，{}, cleanAll = {}".format(args, cleanAll))

    url = "http://platform.fintester.com/api/redisOperation/"
    env = VAR.env

    if cleanAll == True:
        d = {"env": env, "redisKey": "", "operation": "flush", "lockerName": ""}
        post(url, d)
    else:
        for i in args:
            d = {"env": env, "redisKey": i, "operation": "del", "lockerName": ""}
            post(url, d)


def cleanInvestInfo(username):
    """清除用户投资信息,调用运营小工具"""
    d = {
        "env": VAR.env,
        "userName": username,
        "model": "deleteInvest"
    }
    url = "http://platform.fintester.com/api/toolsOfOperation/"
    post(url, d)


def createProduct(prodType="jt", product_Type="周增", tmpId=None, isReserve="", product_term=30, **kwargs):
    """
    创建产品，调用platform的接口
    :param prodType: jt或者dq
    :param product_Type: 周增、月增、双月增、季增
    :param tmpId: 模板id
    :param product_term: 产品期限，定期产品有效，如30,180
    :param kwargs: 其他参数，如募集截止时间
    :return: 
    """
    params = {}
    if prodType == "jt":
        params = {
            "createProductEnv": VAR.env,
            "prodType": prodType,
            "isReserve": isReserve,
            "productName": "{}{}".format(product_Type, time_util.s_time()[2:10]),
            "amountYuan": "",
            "tmpId": tmpId,
            "raiseStartTimeStr": "",
            "calculInterestDateStr": "",
            "extentParams": {}
        }
    elif prodType == "dq":
        params = {
            "createProductEnv": VAR.env,
            "prodType": prodType,
            "isReserve": isReserve,
            "productName": "稳赢{}天-{}".format(product_term, time_util.s_time()[2:9]),
            "amountYuan": "",
            "tmpId": tmpId,
            "raiseStartTimeStr": "",
            "calculInterestDateStr": "",
            "extentParams": {}
        }

    params["extentParams"].update(kwargs)

    url = "http://platform.fintester.com/api/createProduct2/"
    post(url, params)


def getRecordProduct(product_type):
    """访问推荐标的接口，获取推荐的标的，product_type是2时获取新人标，15时获取会员标"""

    if product_type == 2:
        session = login()
        url = DOMAIN + "/fixinws/ws/product/v1/newUserProduct"
        res = wsInterface(session, url)
        logger.info(res)
    elif product_type == 15:
        url = 'http://lcts1.ssjlicai.com/fixinws/ws/product/v1/memberExclusiveProductList?params={%20%22head%22:{%20%22clientId%22:%2212%22},%22body%22:{}}'
        post(url)


def login(userName, password="123456"):
    """登录ssjlc"""
    session = requests.session()

    url = DOMAIN + LOGIN_URL
    loginReturn = wsInterface(session, url, userName=userName, password=password)
    logger.info("登录返回：{}".format(loginReturn))

    assert loginReturn.get('succeed') is True, f'登录接口请求失败！Msg:{loginReturn.get("msg")}'

    return session


def wsInterface(session, url, params=None, verify=False, headers=None, **kwargs):
    """
    封装的ws项目http请求方法，接受session url, param, method， verify, headers 发起http请求并返回json
    :param session: requests session 对象
    :param url: 请求地址
    :param param: 请求参数 形如{key1:value1, key2:value2}
    :param method: 请求方式 默认post
    :param verify: ssl检验 默认关
    :param headers: http headers
    :return: 接口返回内容/None
    """

    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3423.2 Safari/537.36"}

    logger.debug(f'开始调用接口:{url},参数为:params:{params},kwargs:{kwargs}')
    returnJson = None
    if params:
        assert isinstance(params, dict), 'params必须为Dict'
        params.update(kwargs)
    else:
        params = kwargs
    theParam = f'{{"head":{{"clientId":"12","appUDID":"","appVersion":"","channelId":"",' \
               f'"innerMedia":"","outerMedia":"","subClientId":"h5"}},"body":{json.dumps(params)}}}'
    logger.debug(f"请求参数：{theParam}")
    res = session.post(url, data={'params': theParam}, verify=verify, headers=headers)
    logger.info(f'response.status_code:{res.status_code}')
    if res.status_code == 200:
        try:
            returnJson = res.json()

        except (TypeError, json.JSONDecodeError) as e:
            logger.error(f'请求接口:{url}出错,返回:{res.text}\n报错:{e}')
    else:
        logger.error('请求接口失败！响应码非200！')
    logger.debug(f'接口:{url},参数params:{params},kwargs:{kwargs},调用完成 返回:{returnJson}')
    return returnJson


def raiseInterest(pno, interest=0.0200, periods=1, last_period=False):
    """
    计划类加息，定期加息
    :param pno: 
    :param period: 加息的期数
    :param period: 加息多少
    :param last_period: 最后一期
    :return: 
    """
    from decimal import Decimal

    pno = handlePno(pno)

    if pno.startswith("PD"):
        product_info = selectProduct(pno)[0]
        annual_rate = product_info.get("annual_rate")
        basic_annual_rate = product_info.get("basic_annual_rate")

        annual_rate = Decimal(basic_annual_rate) + Decimal(interest)

        annual_rate = str(annual_rate)[0:6]
        return updateProduct(pno, subsidy_rate=interest, annual_rate=annual_rate)

    # 获取最后一期的期数
    product_info = selectProduct(pno)[0]
    last_periods = product_info.get("periods")

    if last_period:
        periods = last_periods

    product_rates = selectProductRate(pno)

    rate_item = None
    for product_rate in product_rates:
        if periods == product_rate.get("periods"):
            rate_item = product_rate
            break

    basic_annual_rate = rate_item.get("basic_annual_rate")

    annual_rate = Decimal(basic_annual_rate) + Decimal(interest)

    annual_rate = str(annual_rate)[0:6]

    sql.exec(
        'UPDATE finance_fixin_product.t_fixin_zc_product_rate SET subsidy_rate = "{}",annual_rate = "{}" WHERE pno = "{}" and periods = {};'.format(
            interest, annual_rate, pno, periods))

    selectProductRate(pno)


def selectProductRate(pno):
    """显示计划类产品的利率信息"""
    res = sql.exec('SELECT * FROM finance_fixin_product.t_fixin_zc_product_rate WHERE pno = "{}";'.format(pno))

    annual_rate = 0
    for item in res:
        annual_rate += item.get("annual_rate")

    logger.info("{}总利率：{}".format(pno, annual_rate))

    return res


def getProducts(product_type=None, is_reserve=False):
    """
    获取在售产品，默认不包含新人标，会员标
    :param product_type: product_type=2时，展示在售新人标，product_type=15时，展示在售会员标
    :param reserve: 等于True时，筛选预约标
    :return: 
    """
    res1 = res2 = []
    is_reserve = 1 if is_reserve is True else 0
    if not product_type:
        res1 = sql.exec(
            'SELECT * FROM finance_fixin_product.t_fixin_zc_product where product_status = 5 and product_type <> 2 and product_type <> 15 AND is_reserve = {};'.format(
                is_reserve))
        res2 = sql.exec(
            'SELECT * FROM finance_fixin_product.t_fixin_periodic_product  where product_status = 5 and product_type <> 2 and product_type <> 15 AND is_reserve = {};'.format(
                is_reserve))

    elif product_type == 2 or product_type == 15:
        res1 = sql.exec(
            'SELECT * FROM finance_fixin_product.t_fixin_zc_product where product_status = 5 and product_type = {} AND is_reserve = {};'.format(
                product_type, is_reserve))
        res2 = sql.exec(
            'SELECT * FROM finance_fixin_product.t_fixin_periodic_product  where product_status = 5 and product_type = {} AND is_reserve = {};'.format(
                product_type, is_reserve))

    pnos1 = ["'{}'".format(i.get("pno")) for i in res1]
    pnos2 = ["'{}'".format(i.get("pno")) for i in res2]

    print("[" + ",".join(pnos1) + "] + [")
    print(",".join(pnos2) + "]:")


def clearRisk(uid):
    """清除风险测评数据"""

    sql.exec('DELETE FROM finance_user_risk.t_risk_rank_score WHERE uid = {};'.format(uid))
    cleanCache(uid)


def testUrl(url, isLogin=False, phoneNumber=None, password="123456"):
    """测试url，isLogin：是否要登录"""
    session = requests.session()
    if isLogin:
        try:
            session = login(phoneNumber, password)
        except Exception as e:
            logger.error("【【【【【【登录失败】】】】】】")
            return

    # url = "https://ssjapp.ssjlicai.com/publicws/ws/v1/isNewHomePageUser"
    d = {"head": {}, "body": {"clientId": 2,
                              "appUDID": "db12f34eda4ad2b3fffaf4321e923cb12991e9349757962419ab140a213eb9f413e887e6c4cf997e154c7f1686576270",
                              "channelId": 0, "version": "11.3.8"}}
    res = wsInterface(session, url, params=d)
    logger.info("返回：{}".format(res))
    return res


def validate3Tags(response):
    """校验返回的tags是否是3个"""
    if not response:
        return
    tags = response.get("data").get("tags")
    if len(tags) != 3:
        logger.error("【【【【【【返回不是B方案】】】】】】")
    else:
        logger.info("★★★★★★返回B方案★★★★★★")


def validateIsNewHomePagerUser(response):
    if not response:
        return

    data = response.get("data")
    if data != True:
        logger.error("【【【【【【灰度异常】】】】】】")
    else:
        logger.info("★★★★★★灰度正常★★★★★★")


def execSql(sqlStr):
    d = {
        "phone": 13302443119,
        "uuid": 2200254632,
        "myname": '董振国',
    }

    for k in d:
        sqlStr = sqlStr.replace("@{}".format(k), '"{}"'.format(str(d.get(k))))

    return sql.exec(sqlStr)


def getAccountInfo(username):
    ret = execSql('select * from finance_fixin_custody.t_user_account where account_name = "{}";'.format(username))[0]
    return ret


def getAccountInfoByPhone(phone):
    ret = execSql('select * from finance_common_usr.t_user_person_info WHERE phone = "{}";'.format(phone))[0]
    ret = execSql('select * from finance_common_usr.t_user_ssj where phone={};'.format(phone))[0]
    return ret


def getAccountInfoByUid(uid):
    ret = execSql('select * from finance_common_usr.t_user_ssj where uid={};'.format(uid))[0]
    return ret


# def getPhoneNumberByName(name):
#     """通过name获取手机号"""
#     try:
#         getAccountInfo(name).get("")



def setAccountInfo(username):
    """主要将finance_fixin_custody.t_user_account表中的余额调整到可体现余额"""
    userInfo = getAccountInfo(username)
    account_no = userInfo.get("account_no")
    balance = userInfo.get("balance")
    sqlStr = 'UPDATE `finance_fixin_custody`.`t_user_account` SET `balance_cash` = {},balance_frost=0,balance_withdraw={} WHERE `account_no` = "{}";'.format(
        balance, balance, account_no)
    sql.exec(sqlStr)
    getAccountInfo(username)


def cleanOtherAccountOperationInfo():
    """清除运营，账户其他的信息"""
    sqlStrs = """
    delete from finance_account.t_user_card_channel where uid=@uuid;
DELETE from finance_account.t_usr_person where uid =@uuid;
delete from finance_account.t_account_card where uid=@uuid;
delete from finance_account.t_trade_account where uid=@uuid;
delete from finance_account.t_usr_account where uid=@uuid;
delete from finance_account.t_account_permission where uid=@uuid;
DELETE from finance_account.t_usr_bankcard where phone=@phone;
DELETE from finance_common_usr.t_user_person_info where phone=@phone;
DELETE from finance_common_usr.t_user_ssj where id=81207;
DELETE from finance_common_usr.t_bankcard_info where bindedmobile =@phone;
DELETE from finance_common_usr.t_user_account_info where uid=@uuid;

delete from finance_operation.t_new_year_open_account where user_name =@myname;
delete from finance_operation.t_user_account_info where user_name =@myname;
delete from finance_operation.t_new_open_account where user_name =@myname;

delete from finance_account.t_user_biz_card_relate where uid = @uuid;
delete from finance_account.t_user_card_channel where uid = @uuid;
delete from finance_account.t_user_account_allocate where uid = @uuid;

delete from finance_operation_data.t_user where name = @myname;
delete from finance_operation_data.t_user_extend where name = @myname;
DELETE FROM finance_operation_data.t_user_invest WHERE uid = @uuid;


DELETE FROM `finance_fixin_trade`.`t_fixin_invest_detail` WHERE uid = @uuid;
DELETE FROM `finance_fixin_cs`.`t_fixin_invest` WHERE uid = @uuid;
DELETE FROM `finance_fixin_cs`.`t_fixin_invest_detail`  WHERE uid = @uuid;
DELETE FROM `finance_operation_act`.`t_act_newcommer_user_cash` WHERE uid = @uuid;
    """
    for line in sqlStrs.split("\n"):
        line = line.strip()
        if line:
            execSql(line)


def getUidByEmail(email):
    sqlStr = 'SELECT * FROM finance_common_usr.t_user_ssj where email = "{}";'.format(email)
    return execSql(sqlStr)[0].get("uid")


def insertWhiteList(uid, tag):
    """插入信息到白名单"""
    sqlStr = """
    INSERT INTO `finance_common_usr`.`t_user_tag`(`uid`, `tag`, `create_time`, `status`, `expire_time`) VALUES ({}, '{}', '2018-09-27 10:53:08', '1', '2019-12-27 10:53:08');
    """

    sqlStr = sqlStr.format(uid, tag)

    sql.exec(sqlStr.strip())

    sql.exec('select * from `finance_common_usr`.`t_user_tag` WHERE uid = "{}";'.format(uid))


def selectWhiteList(uid):
    """查询白名单"""
    sqlStr1 = 'SELECT * FROM `finance_user_colouration`.`t_user_gray_record` WHERE uid = {}'.format(uid)
    sqlStr2 = 'SELECT * FROM `finance_common_usr`.`t_user_tag` WHERE uid = {};'.format(uid)

    sql.exec(sqlStr1)
    sql.exec(sqlStr2)


def changeWhiteList(uid, tag1, tag2):
    """修改tag，将tag1改为tag2"""
    sqlStr1 = 'update `finance_common_usr`.`t_user_tag` set tag = "{}" WHERE uid = {} and tag = "{}"'.format(tag2, uid,
                                                                                                             tag1)
    sqlStr2 = 'SELECT * FROM `finance_common_usr`.`t_user_tag` WHERE uid = {};'.format(uid)

    sql.exec(sqlStr1)
    sql.exec(sqlStr2)

    cleanCache(uid)


def getAllTmps():
    url = "http://platform.fintester.com/api/getAllTmps/"
    post(url)


def deleteFixinInvestRecord(uid):
    """清除非标侧投资记录，构造新人用户"""
    sqlStr = 'DELETE FROM `finance_fixin_trade`.`t_fixin_invest_detail` WHERE uid = "{}";'.format(uid)
    sql.exec(sqlStr)


def clearInvestInfoOnPno(pno):
    """清除一个标的的投资的信息"""
    sqlStrs = """
DELETE FROM `finance_fixin_trade`.`t_fixin_invest_detail` WHERE `pno` = "{pno}";
DELETE FROM `finance_fixin_trade`.`t_fixin_trade_flow` WHERE `pno` = "{pno}";
DELETE FROM `finance_fixin_cs`.`t_fixin_invest` WHERE `pno` = "{pno}";
DELETE FROM `finance_fixin_cs`.`t_fixin_invest_detail` WHERE `pno` = "{pno}";
    """
    for line in sqlStrs.split("\n"):
        line = line.strip()
        if line:
            sql.exec(line.format(pno=pno))

    cleanCache(pno)


def setAccountBalance(username, balance):
    """设置账户的余额"""
    userInfo = getAccountInfo(username)
    account_no = userInfo.get("account_no")
    sqlStr = 'UPDATE `finance_fixin_custody`.`t_user_account` SET `balance_cash` = {} WHERE account_no = "{}"'.format(
        balance, account_no)
    sql.exec(sqlStr)
    getAccountInfo(username)


def searchUserInfo(name):
    """查询集成测试平台的用户信息,目前写死获取手机号"""
    d = {
        "env": VAR.env,
        "name": name,
    }
    url = "http://platform.fintester.com/api/searchUserInfo/"
    response = post(url, d)
    d = response.get("data")[-1]
    phoneNumber = d.get("col2")
    return phoneNumber


def validDetailA(res):
    """检测返回值里面是否是detail-a"""
    products = res.get("data").get("products")
    url = products[0].get("url")

    # url = res.get("data").get("url")

    if "detail-a" in url:
        logger.info("★★★★★★实验组★★★★★★")
        return True


def getPhoneNumbers():
    """扫描 finance_common_usr.t_user_person_info 获取账户"""
    # sqlStr = "select DISTINCT(phone) from finance_common_usr.t_user_person_info";
    # ret = sql.exec(sqlStr)
    # phones =  [r.get("phone") for r in ret if r.get("phone")]
    # print(phones)

    phones = ['15999622104', '15999951376', '15999951642', '17017519814', '17034755963', '17098708565', '17322349528',
              '17322372782', '17328377125', '17503077200', '17512082064', '17603051315', '17606501821', '17620360063',
              '17620453533', '17620460140', '17665498716', '17685729316', '17688715407', '17688737945', '17688968313',
              '17702723337', '17710166380', '17722521992', '17722683230', '17727492240', '17727969150', '17770844260',
              '17786856656', '17858937241', '17862107575', '17865201762', '18003220708', '18026904582', '18026951696',
              '18028736240', '18028795558', '18033079067', '18038051534', '18038086858', '18038089127', '18038814851',
              '18051926786', '18060011762', '18102213515', '18120826048', '18123968419', '18124237540', '18127987149',
              '18128561871', '18134135527', '18138827434', '18142607169', '18145813821', '18146610456', '18148912905',
              '18166036620', '18169454653', '18175757355', '18181612768', '18182076287', '18202035458', '18203054406',
              '18209152587', '18216086911', '18218140076', '18218493686', '18218676908', '18218960001', '18219241300',
              '18221987035', '18235398449', '18242949898', '18250091706', '18257761850', '18263441810', '18263790675',
              '18265105123', '18268895141', '18270282487', '18270847440', '18274190509', '18277363725', '18284594582',
              '18296549827', '18300739652', '18305980070', '18312512920', '18312515589', '18316565506', '18317025257',
              '18318442308', '18320942326', '18326539120', '18328081273', '18328582944', '18333453866', '18339972385',
              '18354529611', '18359109356', '18368173296', '18370247103', '18370995219', '18381094808', '18381811998',
              '18381952690', '18382638328', '18387050100', '18500000001', '18501773108', '18503003038', '18503007743',
              '18503019339', '18503034104', '18504160226', '18510321459', '18519118571', '18519283808', '18519303716',
              '18520521303', '18520880249', '18520880477', '18523307763', '18523607242', '18550169391', '18559863910',
              '18565687532', '18565690760', '18565705013', '18565892498', '18566220082', '18566293998', '18566621159',
              '18566622422', '18566686118', '18566731922', '18566761094', '18566772480', '18566776677', '18570602290',
              '18575575892', '18575597767', '18576418993', '18576708917', '18576776815', '18577322008', '18581228069',
              '18586872413', '18588209707', '18588276236', '18588279549', '18588297978', '18601641827', '18601792772',
              '18603059919', '18604720967', '18606088021', '18607096552', '18607130246', '18607480207', '18611910030',
              '18612141020', '18617115221', '18617123609', '18618171635', '18620310527', '18620340532', '18620922764',
              '18620957565', '18622005721', '18624010105', '18637968719', '18649754382', '18664346340', '18664393872',
              '18664938853', '18664940717', '18665378978', '18665386836', '18665830956', '18666291943', '18670100827',
              '18670229814', '18670792901', '18672584602', '18672771759', '18672854305', '18672886405', '18673046114',
              '18673112144', '18674852475', '18675273490', '18675557268', '18676095784', '18676334341', '18676399253',
              '18676771962', '18676794683', '18679051416', '18680358884', '18680361231', '18681440204', '18681482069',
              '18681502250', '18681565276', '18681568587', '18682000718', '18682019944', '18682032174', '18682062032',
              '18682067482', '18682107475', '18682120285', '18682135407', '18682189961', '18682241012', '18682254268',
              '18682261717', '18682303361', '18682307152', '18682314412', '18682336990', '18682365756', '18682488816',
              '18683260985', '18688668348', '18688726527', '18694982851', '18695607232', '18699619504', '18700000001',
              '18700000002', '18700000004', '18700000011', '18701729516', '18715114929', '18715305011', '18716031929',
              '18718926642', '18720079935', '18720082392', '18720825131', '18720989209', '18721308195', '18723058150',
              '18727295372', '18734911080', '18735153982', '18743232211', '18760324748', '18767411921', '18770087612',
              '18771625873', '18771930582', '18777087373', '18777116941', '18779862271', '18780169721', '18780369065',
              '18788199651', '18788556801', '18792513261', '18810022300', '18810299154', '18810620416', '18810987807',
              '18813293130', '18814444511', '18815078016', '18818860374', '18819429889', '18820936250', '18823351063',
              '18823401262', '18824328352', '18825110245', '18825137742', '18825172487', '18825226314', '18825798809',
              '18826137142', '18826138720', '18826139836', '18826406283', '18840870751', '18842607345', '18843521361',
              '18843779266', '18850494644', '18858190096', '18858558390', '18858665088', '18867868898', '18876824459',
              '18878561056', '18883261090', '18883276250', '18883991830', '18899761313', '18899851724', '18903016624',
              '18904178736', '18910091029', '18922898287', '18923408360', '18923885247', '18923885267', '18925252746',
              '18926565843', '18929379028', '18929526058', '18938662040', '18948334192', '18948736569', '18969239608',
              '18972337897', '18973801975', '18977869318', '18983532073', '18987333105', '18989861405', '18994461293',
              '18998907243']

    res = []
    for phone in phones:
        import time
        time.sleep(3)
        try:
            login(phone)
            res.append(phone)
            logger.info("目前number数，{}   phones：{}".format(len(res), res))
        except Exception as e:
            logger.info("{}不可登陆".format(phone))
            pass


def func():
    t = ['13424377735', '13600000001', '15999569544', '15817303592', '13421836306', '18925252746', '13631511096',
         '18523307763', '13713535461', '15999951376', '18850494644', '15999615961', '18328582944', '13028806961',
         '13387617379', '13632959460', '13530753143', '13530883695', '13534086245', '13538003385', '13556804701',
         '13570919354', '13580517072', '13590241219', '13603074330', '13613013167', '13631223572', '13631393878',
         '13631597157', '13631610648', '13631621707', '13632945571', '13641436263', '13670275386', '13677415326',
         '13682330541', '13682651308', '13682939483', '13686483827', '13691743510', '13713147430', '13717071829',
         '13724373235', '13726201274', '13726259155', '13726261142', '13728734092', '13728881664', '13751122150',
         '13760276565', '13760285225', '13763308813', '13796320002', '13798568950', '13798570615', '13802266481',
         '13811147749', '13823154579', '13825288850', '13826011672', '13826473629', '13828752923', '13828776795',
         '13828784405', '13870660518', '13910283830', '13922398841', '13922444784', '13923001219', '13923764653',
         '13926515286', '13928446626', '13971532303', '13998875091', '15012476018', '15013490495', '15013590958',
         '15013680440', '15014913417', '15104657649', '15118041521', '15118153871', '15180061424', '15217729392',
         '15302656001', '15327266579', '15527905961', '15625863060', '15626210038', '15626477602', '15673419427',
         '15710089075', '15773141476', '15778582387', '15802773901', '15813323840', '15813849160', '15813879355',
         '15816863153', '15817448495', '15817482051', '15818762655', '15872097043', '15889968001', '15908601008',
         '15913023126', '15914098863', '15915710039', '15915979381', '15919874572', '15920400978', '15927098677',
         '15970261800', '15986245742', '15986795213', '15999951642', '17017519814', '17322349528', '17322372782',
         '17328377125', '17512082064', '17606501821', '17620460140', '17665498716', '17688737945', '17722683230',
         '17727492240', '17770844260', '18026904582', '18028795558', '18038051534', '18038086858', '18038089127',
         '18145813821', '18148912905', '18182076287', '18218140076', '18218493686', '18218676908', '18219241300',
         '18221987035', '18270282487', '18277363725', '18305980070', '18312512920', '18318442308', '18370247103',
         '18370995219', '18503019339', '18503034104', '18519118571', '18519283808', '18520880249', '18520880477',
         '18565687532', '18565690760', '18566220082', '18566293998', '18566622422', '18566686118', '18566772480',
         '18570602290', '18575597767', '18576708917', '18576776815', '18607480207', '18620340532', '18620957565',
         '18624010105', '18664346340', '18664938853', '18665378978', '18670100827', '18670229814', '18674852475',
         '18675273490', '18680358884', '18680361231', '18682019944', '18682032174', '18682062032', '18682107475',
         '18682120285', '18682135407', '18682241012', '18682254268', '18682303361', '18682307152', '18700000011',
         '18720825131', '18720989209', '18760324748', '18810022300', '18814444511', '18818860374', '18820936250',
         '18823351063', '18823401262', '18825172487', '18826138720', '18826139836', '18826406283', '18843779266',
         '18883991830', '18899761313', '18922898287', '18923408360', '18923885247', '18926565843', '18929379028',
         '18929526058', '18972337897', '18989861405', '18998907243']

    count = 0
    for phone in t:
        try:
            import time
            time.sleep(3)
            # Common.login(num)
            url = "https://lcts1.ssjlicai.com/fixinws/ws/product/v1/productList"
            # url = "https://lcts1.ssjlicai.com/fixinws/ws/product/v1/memberExclusiveProductList"
            # url = "https://lcts1.ssjlicai.com/fixinws/ws/product/v1/newUserProduct"
            res = testUrl(url, isLogin=True, phoneNumber=phone)
            if validDetailA(res):
                count += 1
            logger.info("{}登录成功".format(phone))
            logger.info("总数量{}，实验组数量{}，占比：{}".format(len(t), count, count / len(t)))
        except Exception as e:
            logger.error(str(e))


def execFile(filePath):
    """执行文件"""

    dirname = os.path.dirname(filePath)
    sys.path.insert(0, dirname)

    dirname = os.path.dirname(os.path.dirname(filePath))
    sys.path.insert(0, dirname)

    basename = os.path.basename(filePath)[:-3]
    m = importlib.import_module(basename)
    main = getattr(m,"main")
    main()
    logger.info("等待.....")
    time.sleep(2)



